package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-post/cache"
	"red-post/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")

	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	book := models.Book{
		Title:   title,
		Content: content,
		Img:     img,
	}

	err := models.DB.Create(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return

	}
	redis_key := "book_Add_" + strconv.Itoa(int(book.ID))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Create(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件数据获取失败",
		})
		return
	}

	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件上传失败",
		})
		return
	}

	url := "http://" + c.Request.Host + "/" + path
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "文件上传成功",
		"data": url,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var book models.Book
	err := models.DB.Where("id = ?", id).First(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": book,
	})
	return
}

func Del(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	err := models.DB.Delete(&models.Book{}, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "book_Add_" + strconv.Itoa(id)
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var book []models.Book

	redis_key := "book_list_"
	models.DB.Find(&book)
	cache.Rdb.Get(cache.Ctx, redis_key)
	jsonData, _ := json.Marshal(book)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": book,
	})
	return
}
